package com.samphanie.ane.core.security.filter;

import com.samphanie.ane.core.properties.AneCoreProperties;
import com.samphanie.ane.core.security.components.CustomSecurityMetadataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;


/**
 * @Author ZSY
 * @createTime 2021/3/13 14:40
 *
 * 动态权限过滤器，用于实现基于路径的动态权限过滤
 */
@Slf4j
@RequiredArgsConstructor
public class CustomSecurityFilter extends AbstractSecurityInterceptor implements Filter {

    private final AneCoreProperties aneCoreProperties;
    private final CustomSecurityMetadataSource customSecurityMetadataSource;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        FilterInvocation invocation = new FilterInvocation(servletRequest, servletResponse, chain);

        // OPTIONS请求直接放行
        if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            invocation.getChain().doFilter(invocation.getRequest(), invocation.getResponse());
            return;
        }

        // 安全路径请求直接放行
        AntPathMatcher matcher = new AntPathMatcher();
        List<String> urls = aneCoreProperties.getIgnoreUrls().getUrls();
        for (String url : urls) {
            if (matcher.match(url, request.getRequestURI())) {
                invocation.getChain().doFilter(invocation.getRequest(), invocation.getResponse());
                return;
            }
        }

        // 此处会调用AccessDecisionManager中的decide方法进行鉴权操作
        InterceptorStatusToken token = super.beforeInvocation(invocation);
        try {
            invocation.getChain().doFilter(invocation.getRequest(), invocation.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }

    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return customSecurityMetadataSource;
    }
}
